const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
var validator = require('validator');

const UserSchema = new mongoose.Schema({
   username: {
      type: String,
      required: [true, '用户名称不能为空'],
      unique: true
   },
   phone: {
      type: String,
      required: [true, '手机号不能为空'],
      validate: {
         validator: function (v) {
            return validator.isMobilePhone(v, 'zh-CN');
         },
         message: '手机号格式错误',
      },
      unique: true,
   },
   password: {
      type: String,
      required: [true, '密码不能为空'],
   },
   avatar: {
      type: String,
      default: 'avatars/avatar1.svg',
   },
   mainGroup: {
      type: String,
      default: '',
   },
});

// 加密密码
UserSchema.pre('save', async function (next) {
   if (!this.isModified('password')) return;
   const salt = await bcrypt.genSalt(10);
   this.password = await bcrypt.hash(this.password, salt);
});

// 对比密码
UserSchema.methods.comparePwd = async function (pwd) {
   const isMatch = await bcrypt.compare(pwd, this.password);
   return isMatch;
};

module.exports = mongoose.model('User', UserSchema);
module.exports.UserSchema = UserSchema;
